// app/controller/users.js
const Controller = require('../controller/baseController')
const { Op } = require('sequelize')
class MenuController extends Controller {
	async list() {
		const { ctx } = this
		let options = {
			order: [['orders'], ['level']],
		}
		const { rows } = await ctx.service.menu.list(options)
		let arr = []
		rows.forEach((element) => {
			// 树形结构是否勾选
			element.dataValues.checked = true
			arr.push(element.dataValues)
		})
		// 当前登录用户的id
		const { id } = ctx.session.userInfo
		// 获取权限编码
		let remarks = []
		await this.app.model
			.query(
				`
			SELECT DISTINCT
			prim 
			FROM
			role_user ur
			LEFT JOIN role_menu rm ON ur.role_id = rm.rid 
			WHERE
			ur.user_id = ?;
			`,
				{ replacements: [id], type: 'SELECT' }
			)
			.then((res) => {
				remarks = res.map((item) => String(item.prim))
			})
		// 过滤出符合的菜单
		let filterArr = []
		for (let i = 0; i < arr.length; i++) {
			if (remarks.includes(arr[i].remark)) {
				arr[i].checked = true
				filterArr.push(arr[i])
			}
		}
		// 树形数组
		// arr = ctx.helper.Tree2(filterArr)
		// arr = ctx.helper.Tree2(arr)
		ctx.helper.success({ data: filterArr })
	}
	async list2() {
		const { ctx } = this
		let options = {
			// 进行level排序

			order: [['level']],
		}

		const data = await ctx.service.menu.list2(options)

		ctx.helper.success({ data })
	}
	// 添加
	async add() {
		const { ctx } = this
		let { name, remark, component } = ctx.request.body
		const { helper } = ctx
		if (!name || !name.trim()) {
			return helper.fail({ msg: '菜单名称不能够为空！' })
		}

		const findRemark = await ctx.model.Menu.findOne({
			where: {
				remark: {
					[Op.eq]: ctx.request.body.remark,
				},
			},
		})
		console.log(ctx.request.body)

		if (findRemark) {
			return helper.fail({ msg: '标识重复' })
		}

		let options = {
			where: {
				name,
			},
		}
		const res = await ctx.service.menu.add(ctx.request.body, options)
		if (res.flag) {
			helper.success({ data: res.data.dataValues, msg: '添加成功' })
		} else {
			helper.fail({ msg: res.msg })
		}
	}
	// 修改

	async update() {
		const { ctx } = this
		let {
			request: { body },
			helper,
		} = ctx
		console.log(body)
		if (!body.id) return helper.fail({ msg: '菜单id必填字段！' })
		const remark = ctx.request.body.remark
		const res = await ctx.service.menu.update(ctx.request.body)
		if (res.flag) {
			helper.success({ msg: '菜单修改成功！' })
		} else {
			helper.fail({ msg: '菜单修改失败！' })
		}
	}
	async del() {
		const { ctx } = this
		let { ids } = ctx.request.body
		const { helper } = this.ctx
		const res = await ctx.service.menu.del(ids)
		if (res.flag) {
			helper.success({ msg: '删除成功！' })
		} else {
			helper.fail({ msg: res.msg })
		}
	}
}
module.exports = MenuController
